package ar.fiuba.tp7552.buildadmin.webactions.planes;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Properties;

import org.apache.fop.apps.Driver;
import org.apache.fop.apps.XSLTInputHandler;

import ar.fiuba.tp7552.buildadmin.model.planes.CobroPlan;
import ar.fiuba.tp7552.buildadmin.model.planes.LiquidacionPlan;
import ar.fiuba.tp7552.buildadmin.model.planes.Plan;
import ar.fiuba.tp7552.buildadmin.pdf.PDFCreator;
import ar.fiuba.tp7552.buildadmin.service.PlanService;
import ar.fiuba.tp7552.buildadmin.webactions.BaseAction;

import com.opensymphony.xwork2.Preparable;

public class PlanAction extends PDFCreator implements Preparable {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private PlanService planService;
	private Plan plan;

	// ~~ Constructor ==============================================================
	public PlanAction(PlanService planService) {
		super();
		this.planService = planService;
	}

	// ~~ Actions ==================================================================
	@Override
	public void prepare() throws Exception {
		if (plan != null && plan.getId() != null) {
			plan = planService.get(plan.getId());
		}
	}
	
	public String load() {
		return BaseAction.SUCCESS;
	}

	public String crearCertificado() {
    	crearPdf();
		return BaseAction.SUCCESS;
	}

	// ~~ getters y setters ========================================================
	public Plan getPlan() {
		return plan;
	}
	public void setPlan(Plan plan) {
		this.plan = plan;
	}

	// ~~ pdfcreator  ========================================================
	public InputStream getInputStream(){
		try{
			return new FileInputStream(new File("certificado.pdf"));
		}catch(Exception e){}
		return null;
   }

    public void crearPdf(){
		String xslParam = "planPago.xsl";
		generarPdf(xslParam);

        return;
	 }
	
	 /***************************************************************************
	 * Renderea al pdf a partir de un xml
	 **************************************************************************/
   @SuppressWarnings("deprecation")
   public byte[] renderXML(XSLTInputHandler input)  throws Exception {
       ByteArrayOutputStream out = new ByteArrayOutputStream();

       Driver driver = new Driver();
       driver.setLogger(null);
       driver.setRenderer(Driver.RENDER_PDF);
       driver.setOutputStream(out);
       try {
           driver.render(input.getParser(), input.getInputSource());                       
       } catch (Exception e) {           
          e.printStackTrace();
       }
       byte[] oPdfBinario = out.toByteArray();
       return oPdfBinario;
   }
   
   public String getXmlAsString() {
       String xsl = "plan.xsl";
       StringBuffer xml = new StringBuffer("");
       DecimalFormat df = new DecimalFormat("###########0.00");

		Properties prop = new Properties();
		try {
			prop.load(this.getClass().getResourceAsStream("/app.properties"));
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	            
    	String pathImg = prop.getProperty("pathPDF") + "img/";

       xml.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
       xml.append("<"+xsl+">");

       //IMAGENES
       xml.append("<signature>" + pathImg + "signature.jpg" + "</signature>");

       //Expensa
       xml.append("<plan>");
       		xml.append("<responsable>" + plan.getResponsable().getNombre() + "</responsable>");

       		xml.append("<monto>" + df.format(plan.getMonto()) + "</monto>");
       		xml.append("<cuotas>" + plan.getCantCuotas() + "</cuotas>");
       		xml.append("<saldoPlan>" + df.format(plan.getSaldoPlan()) + "</saldoPlan>");
       		xml.append("<saldoIntereses>" + df.format(plan.getSaldoIntereses()) + "</saldoIntereses>");

       	xml.append("</plan>");

   		for (LiquidacionPlan item: plan.getLiquidaciones()){
   	   		xml.append("<liquidacion>");
	   			xml.append("<numero>" + item.getNumero() + "</numero>");
		   		SimpleDateFormat date = new SimpleDateFormat("MMMM 'de' yyyy");
		   		xml.append("<periodo>" + date.format(item.getPeriodo()) + "</periodo>");
	       		xml.append("<monto>" + df.format(item.getMonto()) + "</monto>");
	       		xml.append("<intereses>" + df.format(item.getInteresesFinancieros()) + "</intereses>");
	       		xml.append("<punitorio>" + df.format(item.getInteresesPunitorios()) + "</punitorio>");
	       		xml.append("<int2venc>" + df.format(item.getInteres2Vto()) + "</int2venc>");
	       		SimpleDateFormat fulldf = new SimpleDateFormat("dd/MM/yyyy");
	       		xml.append("<vencimiento>" + fulldf.format(item.getVencimiento1()) + "</vencimiento>");
       		xml.append("</liquidacion>");
   		}
       
   		for (CobroPlan item: plan.getCobros()){
   	   		xml.append("<cobro>");
	   			xml.append("<numero>" + item.getNumero() + "</numero>");
	       		SimpleDateFormat fulldf = new SimpleDateFormat("dd/MM/yyyy");
	       		xml.append("<fecha>" + fulldf.format(item.getFecha()) + "</fecha>");
	       		xml.append("<monto>" + df.format(item.getMonto()) + "</monto>");
	       		xml.append("<intereses>" + df.format(item.getInteresesFinancieros()) + "</intereses>");
       		xml.append("</cobro>");
   		}
       

       xml.append("</"+xsl+">");
       return xml.toString();
   }   
	
}
